const {
  registerParamsError,
  userDoesNotExsit,
  userPwdError,
  userLoginError,
} = require("../constant/err.type");
const { checkUserDoesExsit } = require("../service/user.service");
const bcrypt = require("bcryptjs");
const userValidator = async (ctx, next) => {
  // 获取数据进行校验
  const { username, password } = ctx.request.body;
  if (!username || !password) {
    ctx.app.emit("error", registerParamsError, ctx);
    return;
  }
  await next();
};

// 加密中间件
const crpytPassword = async (ctx, next) => {
  const { password } = ctx.request.body;

  const salt = bcrypt.genSaltSync(10);
  // hash保存的是 密文
  const hash = bcrypt.hashSync(password, salt);

  ctx.request.body.password = hash;

  await next();
};

// 登录格式校验

const verifyAppLogin = async (ctx, next) => {
  const { username, password } = ctx.request.body;
  try {
    const res = await checkUserDoesExsit(username);
    if (!username || !password) {
      ctx.app.emit("error", registerParamsError, ctx);
      return;
    }
    // 验证用户是否存在
    if (!res) {
      ctx.app.emit("error", userDoesNotExsit, ctx);
      return;
    }
    // 校验密码是否正确
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit("error", userPwdError, ctx);
      return;
    }
  } catch (error) {
    console.error(err);
    return ctx.app.emit("error", userLoginError, ctx);
  }
  await next();
};
module.exports = {
  userValidator,
  verifyAppLogin,
  crpytPassword,
};
